package com.xywy.fwc.adapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.ScaleAnimation;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xywy.R;
import com.xywy.common.util.ImageLoaderUtil;
import com.xywy.common.util.MD5Util;
import com.xywy.fwc.FwcConstant;
import com.xywy.fwc.FwcNewWebAct;
import com.xywy.fwc.bean.DoctorBean;
import com.xywy.fwc.bean.FormatOnlineTime;
import com.xywy.fwc.bean.VisitTime;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.Request;
import com.xywy.fwc.net.StringParser;
import com.xywy.me.bean.UserKeeper;

public class DoctorAdapter extends BaseAdapter {
	private List<DoctorBean> list;
	private Context context;
	FormatOnlineTime format_time;
	private BitmapDrawable drawable_up;
	private BitmapDrawable drawable_down;
	private SharedPreferences sp;
	private String userid;
	private String mobile;
	
	public DoctorAdapter(List<DoctorBean> list, Context context) {
		this.list = list;
		this.context = context;
		
		Bitmap bp_up = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_up);
		drawable_up = new BitmapDrawable(bp_up);
		Bitmap bp_down = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down);
		drawable_down = new BitmapDrawable(bp_down);
		
		sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(context).getUserid();
//		userid = "15963569";
		SharedPreferences sp = context.getSharedPreferences("config",
				Context.MODE_PRIVATE);
		mobile = sp.getString("mobile", "");
		
	}
	
	public void setList(List<DoctorBean> list){
		this.list = list;
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup arg2) {
		ViewHolder holder;
//		if(convertView == null){
			holder = new ViewHolder();
			convertView = View.inflate(context, R.layout.doctor_item, null);
			holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
			
			holder.tv_reduce = (TextView) convertView.findViewById(R.id.tv_reduce);
			
			holder.tv_ordernum = (TextView) convertView.findViewById(R.id.tv_ordernum);
			
			holder.tv_ordertype = (TextView) convertView.findViewById(R.id.tv_ordertype);
			
			holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
			
			holder.tv_position = (TextView) convertView.findViewById(R.id.tv_position);
			
			holder.tv_department = (TextView) convertView.findViewById(R.id.tv_department);
			
//			holder.tv_realtive_des = (TextView) convertView.findViewById(R.id.tv_realtive_des);
//			
//			holder.tv_realtive = (TextView) convertView.findViewById(R.id.tv_realtive);
			
			holder.tv_hosptial = (TextView) convertView.findViewById(R.id.tv_hosptial);
			
			holder.tv_today = (TextView) convertView.findViewById(R.id.tv_today);
			
			holder.tv_tororrow = (TextView) convertView.findViewById(R.id.tv_tororrow);
			
			holder.tv_week_look = (TextView) convertView.findViewById(R.id.tv_week_look);
		   
			holder.bt_pay = (Button) convertView.findViewById(R.id.bt_pay);
			holder.lin_double = (LinearLayout) convertView.findViewById(R.id.lin_button_double);
			
			holder.lin_pop = (LinearLayout) convertView.findViewById(R.id.lin_pop);
			
			holder.iv_head = (ImageView) convertView.findViewById(R.id.iv_head);
			
			holder.tv1 = (TextView) convertView.findViewById(R.id.tv_1);
			
			holder.tv2 = (TextView) convertView.findViewById(R.id.tv_2);
			
			holder.tv3 = (TextView) convertView.findViewById(R.id.tv_3);
			
			holder.tv4 = (TextView) convertView.findViewById(R.id.tv_4);
			
			holder.tv5 = (TextView) convertView.findViewById(R.id.tv_5);
			
			holder.tv6 = (TextView) convertView.findViewById(R.id.tv_6);
			
			holder.tv7 = (TextView) convertView.findViewById(R.id.tv_7);
			
			holder.bt_pic = (Button) convertView.findViewById(R.id.bt_pic);
			holder.bt_tel = (Button) convertView.findViewById(R.id.bt_tel);
			
			convertView.setTag(holder);
//		}else {
//			holder = (ViewHolder) convertView.getTag();
//		}
		DoctorBean bean = list.get(position);
		
		holder.tv_department.setText(bean.getSubject());
		holder.tv_hosptial.setText(bean.getHospital());
		holder.tv_name.setText(bean.getDocname());
		holder.tv_ordernum.setText(bean.getOrdernum());
//		holder.tv_ordertype.setText("aaaaa");
		holder.tv_position.setText(bean.getJob());
		
		int status = Integer.parseInt(bean.getStatus());
		if(status == 0){
			holder.lin_double.setVisibility(View.GONE);
			holder.bt_pay.setVisibility(View.VISIBLE);
			holder.bt_pay.setTag(position);
			holder.tv_reduce.setText("未付款");
			holder.bt_pay.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					try {
						int position = (Integer) v.getTag();
						Intent intent = new Intent(context,FwcNewWebAct.class);
						
						String url = FwcConstant.H5PAY_URL+"uid="+userid+"&sign="
								+MD5Util.md5(userid+FwcConstant.H5KEY)+
								"&orderid="+list.get(position).getOrderid();
						intent.putExtra("title", "支付页面");
						intent.putExtra("url",url );
						System.out.println("-----------"+url);
						context.startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			//未付款
		}else if (status ==1) {
			//已付款
			long end_time = Long.parseLong(bean.getEndtime())*1000;
			long current_time = System.currentTimeMillis();
			if(end_time >current_time){
				//正常付款的
				holder.tv_reduce.setText((end_time-current_time)/(3600*1000*24)+"天后失效");
				holder.lin_double.setVisibility(View.VISIBLE);
				holder.bt_pay.setVisibility(View.GONE);
				/**
				 * &uid=12234&sign=5d58f7a4faf912b52728085d093252f8&from=familydoctor
				 */
				holder.bt_pic.setTag(position);
				holder.bt_pic.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						try {
							int position = (Integer) v.getTag();
							Intent intent = new Intent(context,FwcNewWebAct.class);
							
							String url = FwcConstant.H5_PIC_URl+"uid="+userid+"&sign="
									+MD5Util.md5(userid+FwcConstant.H5KEY)+
									"&from=familydoctor";
							intent.putExtra("url",url );
							intent.putExtra("title", "图文详情");
							System.out.println("-----------"+url);
							context.startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
				
				holder.bt_tel.setTag(position);
				holder.bt_tel.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						int p = (Integer) v.getTag();
						teleDoctor(p);
						call();
					}
				});
			}else {
				//过期的
				holder.bt_pay.setTag(position);
				
				holder.tv_reduce.setText("已过期");
				holder.lin_double.setVisibility(View.GONE);
				holder.bt_pay.setVisibility(View.VISIBLE);
				holder.bt_pay.setText("立即续费");
				
				holder.bt_pay.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						try {
							int position = (Integer) v.getTag();
							Intent intent = new Intent(context,FwcNewWebAct.class);
							
							String url = FwcConstant.H5X_URl+"uid="+userid+"&sign="
									+MD5Util.md5(userid+FwcConstant.H5KEY)+
									"&did="+list.get(position).getDocid()+"&os=android";
							intent.putExtra("url",url );
							intent.putExtra("title", "立即续费");
							System.out.println("-----------"+url);
							context.startActivity(intent);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		}else if (status ==-1) {
			//失效
			holder.tv_reduce.setText("已失效");
			holder.lin_double.setVisibility(View.GONE);
			holder.bt_pay.setVisibility(View.GONE);
			holder.bt_pay.setText("订单失效");
		}
		
		int order_type = Integer.parseInt(bean.getCategory());
		if(order_type == 1){
			holder.tv_ordertype.setText("包周"+bean.getAmount());
		}else if (order_type ==2) {
			holder.tv_ordertype.setText("包月"+bean.getAmount());
		}else {
			holder.tv_ordertype.setText("免费"+bean.getAmount());
		}
		
//		if(!"0".equals(bean.getAssocnum())){
//			holder.tv_realtive.setText(bean.getAssoc_member().toString());
//		}
//		holder.tv_reduce.setText(bean.getEndtime()+"天后服务到期");
		holder.tv_time.setText(getDate(bean.getOrdertime()));
		format_time = new FormatOnlineTime();
		List<VisitTime> visit_times = getDataofWeek(bean.getOnlinetime());
		
		holder.tv1.setText(visit_times.get(0).getStr());
		holder.tv2.setText(visit_times.get(1).getStr());
		holder.tv3.setText(visit_times.get(2).getStr());
		holder.tv4.setText(visit_times.get(3).getStr());
		holder.tv5.setText(visit_times.get(4).getStr());
		holder.tv6.setText(visit_times.get(5).getStr());
		holder.tv7.setText(visit_times.get(6).getStr());
		TextView tvs[] = {
				holder.tv1,
				holder.tv2,
				holder.tv3,
				holder.tv4,
				holder.tv5,
				holder.tv6,
				holder.tv7,
				
		};
		for(int i=0;i<tvs.length;i++){
			if(tvs[i].getText().toString().contains("不出诊")){
				tvs[i].setVisibility(View.GONE);
			}
		}
		holder.tv_today.setText(current_day_str);
		holder.tv_tororrow.setText(tomorrow_day_str);
		holder.tv_week_look.setText("一周坐诊时间");
		
		holder.lin_pop.setVisibility(View.GONE);
		holder.tv_week_look.setTag(holder.lin_pop);
		
		holder.tv_week_look.setOnClickListener(new MyListener(holder,visit_times));
		
		ImageLoaderUtil.displayHeadImage(bean.getPhoto(), holder.iv_head);
		
		return convertView;
	}
	
	class ViewHolder{
		public TextView tv_time;
		public TextView tv_reduce;
		public TextView tv_ordernum;
		public TextView tv_ordertype;
		public TextView tv_name;
		public TextView tv_position;
		public TextView tv_department;
//		public TextView tv_realtive_des;
//		public TextView tv_realtive;
		public TextView tv_hosptial;
		public TextView tv_today;
		public TextView tv_tororrow;
		public TextView tv_week_look;
		public Button bt_pay;
		public LinearLayout lin_double;
		public LinearLayout lin_pop;
		public ImageView iv_head;
		public int popup_status;
		
		public TextView tv1;
		public TextView tv2;
		public TextView tv3;
		public TextView tv4;
		public TextView tv5;
		public TextView tv6;
		public TextView tv7;
		
		public Button bt_pic;
		public Button bt_tel;
	}
    
	
	private String getDate(String time){
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
		Date date = new Date(Long.parseLong(time)*1000);
		return sdf.format(date);
	}
	
	
	String weekstr[] = {
			"周一",
			"周二",
			"周三",
			"周四",
			"周五",
			"周六",
			"周日",
	};
	
	private String current_day_str="";
	private String tomorrow_day_str="";
	private List<VisitTime> getDataofWeek(String str){
		if(str == null || "".equals(str)){
			List<VisitTime> times = new ArrayList<VisitTime>();
			for(int i=0;i<7;i++){
				VisitTime vt = new VisitTime();
				List<String> list = new ArrayList<String>();
	        	vt.setHour_str(list);
				vt.getHour_str().add("不出诊");
				times.add(vt);
			}
			return times;
		}
		 String temp[] = str.split(",");
	        // 49 50 51 52 53 54 55 56 57
	        List<VisitTime> times = new ArrayList<VisitTime>();
	        for(int i=0;i<7;i++){
	        	VisitTime vt = new VisitTime();
	        	vt.setEnd_hour(-1);
	        	vt.setStart_hour(-1);
	        	List<String> list = new ArrayList<String>();
	        	vt.setHour_str(list);
	        	times.add(vt);
	        }
	        int current_week = 0;
	        for(int i=0;i<temp.length;i++){
	        	String tempStr = temp[i];
	        	int x = tempStr.charAt(0);
	        	boolean week_change = true;
	        	if(x == current_week || current_week ==0){
	        		week_change = false;
	        	}else {
	        		VisitTime vt = times.get(x-50);
	        		if(vt.getStart_hour() != -1&& vt.getEnd_hour() != -1){
	        			if(vt.getStart_hour() == vt.getEnd_hour()){
        					vt.setEnd_hour(vt.getStart_hour()+1);
        				}
	        			vt.getHour_str().add(vt.getStart_hour()+":00"+"-"+vt.getEnd_hour()+":00");
	        		}
				}
	        	current_week = x;
	        	VisitTime vt = times.get(x-49);
	        	vt.setWeek(weekstr[x-49]);
	        	String dayStr[] = tempStr.split("00");
	        	if(dayStr.length ==1){
	        		vt.getHour_str().add("不出诊");
	        	}else {
	        		int day = Integer.parseInt(dayStr[1]);
	        		if(vt.getStart_hour() ==-1){
	        			vt.setStart_hour(day);
	        		}
	        		if(vt.getEnd_hour() != -1){
	        			int diff = day - vt.getEnd_hour();
	        			if(diff >1 && !week_change){
	        				if(vt.getStart_hour() == vt.getEnd_hour()){
	        					vt.setEnd_hour(vt.getStart_hour()+1);
	        				}
	        				vt.getHour_str().add(vt.getStart_hour()+":00"+"-"+vt.getEnd_hour()+":00");
	        				vt.setStart_hour(day);
	        			}
	        		}
	        		vt.setEnd_hour(day);
				}
	        }
	        for(VisitTime vt:times){
	        	System.out.println(vt.getHour_str());
	        }
	        
	        Calendar calendar = Calendar.getInstance();
			int current_week1 = calendar.get(Calendar.DAY_OF_WEEK)-1; //这个是真实的日期
			calendar.add(Calendar.DAY_OF_WEEK, 1);
			int tomorrow_week = calendar.get(Calendar.DAY_OF_WEEK)-1;
			if(current_week1 ==0){
				current_day_str = times.get(6).getStr();
			}else {
				current_day_str = times.get(current_week1-1).getStr();
			}
			
			if(tomorrow_week ==0){
				tomorrow_day_str = times.get(6).getStr();
			}else {
				tomorrow_day_str = times.get(tomorrow_week-1).getStr();
			}
			if(current_day_str != null && current_day_str.contains("周")){
				current_day_str = current_day_str.substring(2, current_day_str.length());
			}
			
            if(tomorrow_day_str != null && tomorrow_day_str.contains("周")){
            	tomorrow_day_str = tomorrow_day_str.substring(2, tomorrow_day_str.length());
			}
	        return times;
	}
	
	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
	
	class MyListener implements OnClickListener{
        private ViewHolder holder;
        List<VisitTime> visit_times;
		public MyListener(ViewHolder holder ,List<VisitTime> visit_times) {
			this.holder = holder;
			this.visit_times = visit_times;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			if(holder.popup_status == 0){
				holder.lin_pop.setVisibility(View.VISIBLE);
				ScaleAnimation scalanim = new ScaleAnimation(1,1,0,1);
				scalanim.setDuration(500);
				holder.lin_pop.startAnimation(scalanim);
				holder.popup_status =1;
				
				Drawable drawables[] = holder.tv_week_look.getCompoundDrawables();
				drawable_up.setBounds(drawables[2].getBounds());
				drawable_down.setBounds(drawables[2].getBounds());
				
				holder.tv_week_look.setCompoundDrawables(null, null, drawable_down, null);
			}else {
				ScaleAnimation scalanim = new ScaleAnimation(1,1,1,0);
				scalanim.setDuration(500);
				holder.lin_pop.startAnimation(scalanim);
				holder.lin_pop.setVisibility(View.GONE);
				holder.popup_status =0;
				Drawable drawables[] = holder.tv_week_look.getCompoundDrawables();
				drawable_up.setBounds(drawables[2].getBounds());
				drawable_down.setBounds(drawables[2].getBounds());
				holder.tv_week_look.setCompoundDrawables(null, null, drawable_up, null);
			}
		}
		
	}
	/**
	 * 拨打电话
	 * @param position
	 * 
 * usermobile=13718825134&docmobile=15210241210&token=
 */
    public void teleDoctor(int position){
    	try {
			DoctorBean bean = list.get(position);
			String token = MD5Util.md5(mobile+bean.getDocmobile()+"192959ff06b5be7bd858c14d0ce3394c");
			token = token.substring(0, 16);
			System.out.println(token.length());
			String url = FwcConstant.TEL_URL+"usermobile="+mobile+
					"&docmobile="+bean.getDocmobile()+"&token="
					+token;
			System.out.println(url);
			Request.requestData(new StringParser(), new DataCallBack<String>() {
	
				@Override
				public void dataCall(String t) {
					System.out.println(t);
				}
			}, url);
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
    
    private void call() {
    	String number = "tel://4001890120";
    	 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(number));    
         context.startActivity(intent);    
	}
}
